import json

from shop.model.goods import Goods
from shop.model.goods_collection import GoodsCollection
from shop.util.time_operation import TimeClass


class CollectionHandler:
    '''
    收藏商品相关操作类
    '''

    def __init__(self, user_id, goods_info=None):
        self.user_id = user_id
        self.goods_info = goods_info

    def save_collection(self):
        '''
        保存收藏记录
        :return:
        '''
        if not self.goods_info:
            raise Exception("goods can't be null")
        goods_info_dict = json.loads(self.goods_info)
        goods_id = goods_info_dict.get("goodsId")
        # 保存商品信息
        Goods.save_goods(goods_id, self.goods_info)
        # 保存用户浏览记录
        GoodsCollection.save_one_user_browse_record(self.user_id, goods_id)

    def get_collection(self, page, page_size):
        '''
        获取用户的收藏记录
        :return:
        '''
        some_ub, total_num = GoodsCollection.get_one_user_browse_record(self.user_id, page, page_size)
        # 得到所有的goods_id列表
        goods_id_list = []
        goods_id_create_time_dict = {}
        for ub in some_ub:
            create_time = ub.create_time
            goods_id = ub.goods_id
            goods_id_create_time_dict[goods_id] = TimeClass.get_str_by_datetime(create_time)
            goods_id_list.append(goods_id)
        # 根据goods_id获取所有的商品
        some_goods = Goods.get_goods_by_goods_id_list(goods_id_list)
        # 重新格式化结果
        res = []
        for one_goods in some_goods:
            json_goods = one_goods.to_json()
            goods_id = one_goods.id
            json_goods["view_time"] = goods_id_create_time_dict.get(goods_id)
            res.append(json_goods)
        return {
            "goods": res,
            "total": total_num
        }
